package com.x.chalk.service.impl;

import com.x.chalk.dao.UsefulNewsCommentDao;
import com.x.chalk.dao.UsefulNewsDao;
import com.x.chalk.dto.UsefulNewsCommentDto;
import com.x.chalk.entity.UsefulNewsComment;
import com.x.chalk.service.intf.UsefulNewsCommentService;
import com.x.chalk.util.BaiduCensorUtil;
import com.x.chalk.vo.R;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.sql.SQLException;
@Service
public class UsefulNewsCommentServiceImpl implements UsefulNewsCommentService {

    private final UsefulNewsCommentDao dao;
    private final UsefulNewsDao usefulNewsDao;

    public UsefulNewsCommentServiceImpl(UsefulNewsCommentDao dao, UsefulNewsDao usefulNewsDao) {
        this.dao = dao;
        this.usefulNewsDao = usefulNewsDao;
    }

    /**
     * 进行评论或评论回复
     * @param dto
     * @param token
     * @return
     */
    @Override
    @Transactional(rollbackFor = SQLException.class)
    public R add(UsefulNewsCommentDto dto, String token) {
        //获取当前用户id
        Integer uid =Integer.parseInt(token);
        //校验传进参数
        if (dto!=null){
            if (StringUtils.hasLength(dto.getInfo())){
                //文本内容审核
                if (BaiduCensorUtil.textCensor(dto.getInfo())) {
                    //检测通过添加评论
                    dao.insert(new UsefulNewsComment(dto.getUsefulnewsId(),uid, dto.getInfo(), 0));
                    //对应文章评论数加一
                    usefulNewsDao.updateComment(dto.getUsefulnewsId(), 1);
                    return R.ok();
                }else {
                    return R.fail("文本内容违规");
                }
            }
        }
        return R.fail();
    }

    /**
     * 评论回复
     * @param dto
     * @param token
     * @return
     */
    @Override
    @Transactional(rollbackFor = SQLException.class)
    public R addReply(UsefulNewsCommentDto dto, String token) {
        //获取当前用户id
        Integer uid =Integer.parseInt(token);
        //校验传进参数
        if (dto!=null){
            if (StringUtils.hasLength(dto.getInfo())){
                //文本内容审核
                if (BaiduCensorUtil.textCensor(dto.getInfo())) {
                    //检测通过添加评论
                    dao.insert(new UsefulNewsComment(dto.getUsefulnewsId(),uid, dto.getInfo(), dto.getCommentId()));
                    return R.ok();
                }else {
                    return R.fail("文本内容违规");
                }
            }
        }
        return R.fail();
    }

    /**
     * 查询评论
     * @param
     * @return
     */
    @Override
    public R all(Integer usefulnewsId) {
        return null;
    }
}
